package cn.com.callback

import cn.com.elite.Util
import cn.com.kh.KHDBConfig
import net.sf.json.JSONArray
import net.sf.json.JSONObject
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import cn.com.elite.EliteBean
import org.springframework.jdbc.core.JdbcTemplate;

public class autoCMSendMessage implements CallBackInvoke {
    private static final Logger log = LoggerFactory.getLogger(autoCMSendMessage.class);

    private static String CM_ProductToken = "b4b49728-9eda-4f10-980e-da21ac4372b7";
    private static String CM_AccountID = "154d3c2e-472c-40df-a0e9-597647da4069";
    private static String CM_ChannelRequestId = "f47f65e1-52dd-4607-818a-67ec91c658ff";

    public void doCallBack(EliteBean eliteBean, String callBack, Map map, String paramString) {

        CM_ProductToken = KHDBConfig.getParamConfig(eliteBean, "CM_ProductToken");
        CM_AccountID = KHDBConfig.getParamConfig(eliteBean, "CM_AccountID");
        CM_ChannelRequestId = KHDBConfig.getParamConfig(eliteBean, "CM_ChannelRequestId");

        //查找待发送任务
        List getSmsSelectSQL = eliteBean.chaxun_sql('''Select R1.Documentout_Guid,
                                                           R1.Doctype,
                                                           R1.Documentto,
                                                           R1.Documentpath,
                                                           R1.Documentpath2,
                                                           R1.Documentfrom,
                                                           R1.Template_Id,
                                                           R3.Templatname,
                                                           R3.Facebooknamespaceid,
                                                           R2.Languagetype,
                                                           R1.Reference
                                                      From Cm_Documentout R1
                                                      Left Join Cm_Templates_Languages R2
                                                        On R1.Template_Id = R2.Rec_Guid
                                                      Left Join Cm_Templates R3
                                                        On R2.Templates_Id = R3.Id
                                                     Where R1.Doctype = 9
                                                       And R1.Status = 0
                                                       And R1.Trialcount < R1.Trialcountlimit
                                                     Order By R1.Createddate''', "dataSource");
        log.debug("SQL获取待发送数据量:" + getSmsSelectSQL.size());

        for (int i = 0; i < getSmsSelectSQL.size(); i++) {

            Map selectResultcm = getSmsSelectSQL.get(i);
            String Documentout_Guid = selectResultcm.get("Documentout_Guid");
            String Doctype = selectResultcm.get("Doctype");
            String Documentfrom = selectResultcm.get("Documentfrom");
            String Documentto = selectResultcm.get("Documentto");
            String Documentpath = selectResultcm.get("Documentpath");
            String Documentpath2 = selectResultcm.get("Documentpath2");
            String Template_Id = selectResultcm.get("Template_Id");
            String Templatname = selectResultcm.get("Templatname");
            String Facebooknamespaceid = selectResultcm.get("Facebooknamespaceid");
            String Languagetype = selectResultcm.get("Languagetype");
            String Reference = selectResultcm.get("Reference");

            if (Doctype == "9") {
                doSendCMSMS(eliteBean, Documentout_Guid, Documentfrom, Documentto, Documentpath, Documentpath2, Template_Id, Templatname, Facebooknamespaceid, Languagetype, Reference);

            } else {
                log.warn("未知的消息类型-本条任务结束");
            }
        }

    }

    /**
     * 发送短信消息
     * @param s1
     * @param s2
     * @param s3
     */
    public static void doSendCMSMS(EliteBean eliteBean, String Documentout_Guid, String Documentfrom, String Documentto, String Documentpath, String Documentpath2, String Template_Id, String Templatname, String Facebooknamespaceid, String Languagetype, String Reference) {

        // 开始准备发送
        int Oper_Num = 0;
        JSONObject sendResultJson = sendCMSms(eliteBean, Documentout_Guid, Documentfrom, Documentto, Documentpath, Documentpath2, Template_Id, Templatname, Facebooknamespaceid, Languagetype, Reference);
        // 获取数据源
        JdbcTemplate jt = new JdbcTemplate(eliteBean.getDataSource());

        if (sendResultJson.getString("errorCode") == "0") {
            // 发送成功
            String updateSQL = "Update Cm_Documentout Set Status = '1', Failcode = '0', Faildescription = ?, Trialcount = Trialcount + 1, Lasttrydatetime = Now(), Finishdatetime = Now() Where Documentout_Guid = ?";

            Oper_Num = jt.update(updateSQL, sendResultJson.toString(), Documentout_Guid);
            log.debug("将发送结果发送成功同步到Cm_Documentout 数量：" + Oper_Num);
        } else {
            // 发送失败
            String failCode = sendResultJson.getString("errorCode");
            String updateSQL = "Update Cm_Documentout Set Status = Case When Trialcount + 1 >= Trialcountlimit Then '-1' Else Status End, Failcode = '-1', Faildescription = ?, Trialcount = Trialcount + 1, Lasttrydatetime = Now() Where Documentout_Guid = ?";
            Oper_Num = jt.update(updateSQL, sendResultJson.toString(), Documentout_Guid);
            log.debug("将发送结果发送失败同步到Cm_Documentout 数量：" + Oper_Num);
        }

        // 将发送结果同步到DocumentOut
        try {
            String SyncSQL = '''Replace Into Documentout
                              (Documentout_Guid,
                               Doctype,
                               Status,
                               Trialcount,
                               Trialcountlimit,
                               Template_Id,
                               Documentpath,
                               Documentpath2,
                               Comments,
                               Documentfrom,
                               Documentto,
                               Modifiedby,
                               Modifieddate,
                               Handleby_Id,
                               Handlegroup_Id,
                               Createdby,
                               Createddate,
                               Lasttrydatetime,
                               Failcode,
                               Faildescription,
                               Finishdatetime)
                              Select Documentout_Guid,
                                     Doctype,
                                     Status,
                                     Trialcount,
                                     Trialcountlimit,
                                     Template_Id,
                                     Documentpath,
                                     Documentpath2,
                                     Comments,
                                     Documentfrom,
                                     Documentto,
                                     Modifiedby,
                                     Modifieddate,
                                     Createdby,
                                     CreatedGroup,
                                     Createdby,
                                     Createddate,
                                     Lasttrydatetime,
                                     Failcode,
                                     Faildescription,
                                     Finishdatetime
                                From Cm_Documentout
                               Where (Status = '1' Or Status = '-1')
                                 And Documentout_Guid = ?''';
            Oper_Num = jt.update(SyncSQL, Documentout_Guid);
            log.debug("将发送结果同步到DocumentOut 数量：" + Oper_Num);
        } catch (Exception e1) {
            log.warn("将发送结果同步到DocumentOut异常：", e1);

        }

    }

    public static JSONObject sendCMSms(EliteBean eliteBean, String Documentout_Guid, String Documentfrom, String Documentto, String Documentpath, String Documentpath2, String Template_Id, String Templatname, String Facebooknamespaceid, String Languagetype, String Reference) {
        JSONObject resultSendSms = new JSONObject();

        log.debug("sendAliSms参数-Documentout_Guid:" + Documentout_Guid + " Documentto:" + Documentto + " Documentpath2:" + Documentpath2 + " Documentfrom:" + Documentfrom + " Template_Id:" + Template_Id);

        try {
            // 获取WhatsApp发送地址URL
            String CM_SendMessage_URL = KHDBConfig.getAPIURL(eliteBean, "CM_SendMessage");
            log.debug("调用CM短信发送URL：" + CM_SendMessage_URL);

            // 处理头文件
            Map<String, String> headParams = new HashMap<String, String>();
            headParams.put("Content-Type", "application/json");

            // 获取发送原始报文
            String sendBody = KHDBConfig.getParamConfig(eliteBean, "CM_SendTemplateJson");
            JSONObject sendBodyObj = JSONObject.fromObject(sendBody);

            sendBodyObj.getJSONObject("messages").put("reference", Reference);

            // 发送Token
            sendBodyObj.getJSONObject("messages").getJSONObject("authentication").put("producttoken", CM_ProductToken);

            // 发送人
            sendBodyObj.getJSONObject("messages").getJSONArray("msg").getJSONObject(0).put("from", Documentfrom);

            // 发送目标号码
            JSONObject toObj = new JSONObject();
            toObj.put("number", Documentto);
            sendBodyObj.getJSONObject("messages").getJSONArray("msg").getJSONObject(0).getJSONArray("to").add(toObj);

            // 实际发送内容
            sendBodyObj.getJSONObject("messages").getJSONArray("msg").getJSONObject(0).getJSONObject("body").put("content", Documentpath);

            // 命名空间
            sendBodyObj.getJSONObject("messages").getJSONArray("msg").getJSONObject(0).getJSONObject("richContent").getJSONArray("conversation").getJSONObject(0).getJSONObject("template").getJSONObject("whatsapp").put("namespace", Facebooknamespaceid);

            // 模板名称
            sendBodyObj.getJSONObject("messages").getJSONArray("msg").getJSONObject(0).getJSONObject("richContent").getJSONArray("conversation").getJSONObject(0).getJSONObject("template").getJSONObject("whatsapp").put("element_name", Templatname);

            // 语言类型
            sendBodyObj.getJSONObject("messages").getJSONArray("msg").getJSONObject(0).getJSONObject("richContent").getJSONArray("conversation").getJSONObject(0).getJSONObject("template").getJSONObject("whatsapp").getJSONObject("language").put("code", Languagetype);

            // 参数对象
            JSONObject bodyComObj = new JSONObject();
            bodyComObj.put("type", "body");
            JSONArray bodyParamArr = JSONArray.fromObject(Documentpath2);
            bodyComObj.put("parameters", bodyParamArr);
            sendBodyObj.getJSONObject("messages").getJSONArray("msg").getJSONObject(0).getJSONObject("richContent").getJSONArray("conversation").getJSONObject(0).getJSONObject("template").getJSONObject("whatsapp").getJSONArray("components").add(bodyComObj);

            log.debug("调用CM短信发送报文：" + sendBodyObj.toString());

            String resultInfo = Util.doHttpPostUseHead(CM_SendMessage_URL, sendBodyObj.toString(), "UTF-8", 120000, 0, headParams);
            log.debug("调用CM短信发送返回：" + resultInfo);

            resultSendSms = JSONObject.fromObject(resultInfo);

            log.debug("调用CM短信发送结果：" + resultSendSms.toString());

        } catch (Exception e1) {
            log.error("调用CM短信发送异常：", e1);
            resultSendSms.put("errorCode", "-1");
            resultSendSms.put("messages", e1.getMessage());

        }

        return resultSendSms;
    }
}
